package com.linkage.seapeak.activity.vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProTalkActivity;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.seapeak.activity.message.MultiSendActivity;
import com.linkage.seapeak.activity.message.ScreenUserActivity;
import com.linkage.seapeak.activity.message.ScreenVoteUserActivity;
import com.linkage.seapeak.adapter.CrediterAdapter;
import com.linkage.seapeak.adapter.CrediterNewAdapter;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.CrediterNewUser;
import com.linkage.seapeak.pojo.CrediterUser;
import com.linkage.seapeak.view.CreditorOrderDialog;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 债权人选择人员
 */
public class CreditorMultiSelectActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    List<CrediterNewUser> userList;
    AYSwipeRecyclerView recyclerView;
    CrediterNewAdapter adapter;

    TextView count_member, order_item, all_select, screen_member;
    TextView menu;


    String projectId;

    Integer committee;
    Boolean onlineStatus;
    Boolean kindTax;
    Boolean kindGuarantee;
    Boolean kindOther;
    Boolean kindOrdinary;
    Double minAmountDeclared;
    Double maxAmountDeclared;
    Double minConfirmAmount;
    Double maxConfirmAmount;
    String processStatus;

    String orderBy = "desc";
    String orderColumn = "";

    int pageNo = 1;
    int pageSize = 20;
    String type = "0";
    String seltype = "0";

    //已选择人的ids;
    List<String> selectIds;
    List<String> alreadySelectIds;
    boolean canSelectAlready = true;

    boolean isAll = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creditor_multi_select, "添加成员");
        init();
    }

    private void init() {
        projectId = getIntent().getStringExtra("projectId");
        canSelectAlready = getIntent().getBooleanExtra("canSelectAlready", true);
        alreadySelectIds = getIntent().getStringArrayListExtra("alreadySelectIds");
        if (alreadySelectIds == null)
            alreadySelectIds = new ArrayList<>();
        selectIds = new ArrayList<>();
        selectIds.addAll(alreadySelectIds);

        try {
            type = getIntent().getStringExtra("type");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (type == null)
            type = "2";

        try {
            seltype = getIntent().getStringExtra("seltype");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (seltype == null)
            seltype = "0";

        recyclerView = findViewById(R.id.member_list);
        count_member = findViewById(R.id.count_member);
        all_select = findViewById(R.id.all_select);
        order_item = findViewById(R.id.order_item);
        screen_member = findViewById(R.id.screen_member);

        userList = new ArrayList<>();
        recyclerView.setOnRefreshLoadLister(this);
        recyclerView.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        adapter = new CrediterNewAdapter(CreditorMultiSelectActivity.this, userList, true);
        recyclerView.setAdapter(adapter);
        recyclerView.startLoadFirst();
        recyclerView.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                if (!canSelectAlready && alreadySelectIds.contains(userList.get(position).getId()))
                    return;

                boolean itemCheck = userList.get(position).isCheck;
                userList.get(position).isCheck = !itemCheck;
                if (!itemCheck) {
                    selectIds.add(userList.get(position).getId());
                } else {
                    selectIds.remove(userList.get(position).getId());
                }
                adapter.notifyDataSetChanged();
                menu.setText("完成(" + selectIds.size() + ")");
            }
        });

        all_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAll = !isAll;
                all_select.setText(isAll ? "取消" : "全选");
                adapter.setAllSelect(isAll);
                selectIds.clear();
                if (isAll) {
                    for (CrediterNewUser idStr : userList) {
                        selectIds.add(idStr.getId());
                    }
                }
                menu.setText("完成(" + selectIds.size() + ")");
                adapter.notifyDataSetChanged();
            }
        });

        order_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final CreditorOrderDialog dialog = new CreditorOrderDialog(CreditorMultiSelectActivity.this);
                dialog.init(CreditorMultiSelectActivity.this, orderColumn, orderBy);
                dialog.setSureListener(new CreditorOrderDialog.OnSureListener() {
                    @Override
                    public void onSure(int orderType, int orderOrien) {
//                        declareTime 申报时间
//                        confirmTime 确认时间
//                        amountDeclared 申报金额
//                        confirmAmount 确认金额
                        if (orderType == 1)
                            orderColumn = "confirmAmount";
                        else if (orderType == 2)
                            orderColumn = "amountDeclared";
                        else if (orderType == 3)
                            orderColumn = "confirmTime";
                        else if (orderType == 4)
                            orderColumn = "declareTime";
                        orderBy = orderOrien == 2 ? "asc" : "desc";
                        getCreditorList(true);
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });

        screen_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CreditorMultiSelectActivity.this, ScreenUserActivity.class);
                intent.putExtra("seltype", seltype);
                startActivityForResult(intent, 0x11);
            }
        });

        menu = (TextView) addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectIds == null || selectIds.size() == 0) {
                    showToast("请至少选择一个成员");
                    return;
                }

                List<CrediterNewUser> selectList = new ArrayList<>();
                for (int i = 0; i < userList.size(); i++) {
                    CrediterNewUser user = userList.get(i);
                    if (user != null && user.isCheck) {
                        selectList.add(user);
                    }
                }

                if ("1".equalsIgnoreCase(type)) {
                    String seluserName = "";
                    String seluserId = "";
                    for (int i = 0; i < selectList.size(); i++) {
                        CrediterNewUser user = selectList.get(i);
                        if (user != null) {
                            seluserName = seluserName + user.getCreditorname() + ",";
                            seluserId = seluserId + user.getId() + ",";
                        }
                    }
                    Intent intent = new Intent(CreditorMultiSelectActivity.this, CreateProTalkActivity.class);
                    intent.putExtra("seluserName", seluserName);
                    intent.putExtra("seluserId", seluserId);
                    setResult(RESULT_OK, intent);
                    finish();
                    return;
                } else if ("2".equalsIgnoreCase(type)){
//                    计算新增的用户
                    List<CrediterNewUser> appendList = new ArrayList<>();
                    for (CrediterNewUser user : selectList) {
                        if (alreadySelectIds.contains(user.getId()))
                            continue;
                        else
                            appendList.add(user);
                    }
                    Intent intent = new Intent();
                    intent.putExtra("userList", (Serializable) selectList);
                    intent.putExtra("appendList", (Serializable) appendList);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    Intent intent = new Intent(CreditorMultiSelectActivity.this, MultiSendActivity.class);
                    intent.putExtra("projectId", projectId);
                    intent.putExtra("userList", (Serializable) selectList);
                    startActivity(intent);
                    finish();
                }
            }
        }, "下一步", 0));
        if ("0".equalsIgnoreCase(type)) {
            menu.setText("下一步");
        } else {
            menu.setText("完成");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == RESULT_OK && data != null) {
            committee = data.getIntExtra("committee", 1);
            int online = data.getIntExtra("onlineStatus", 0);
            if (online == 0)
                onlineStatus = null;
            else if (online == 1)
                onlineStatus = true;
            else
                onlineStatus = false;
            kindTax = data.getBooleanExtra("kindTax", false);
            kindGuarantee = data.getBooleanExtra("kindGuarantee", false);
            kindOther = data.getBooleanExtra("kindOther", false);
            kindOrdinary = data.getBooleanExtra("kindOrdinary", false);
            minAmountDeclared = data.getDoubleExtra("minAmountDeclared", 0);
            maxAmountDeclared = data.getDoubleExtra("maxAmountDeclared", 0);
            minConfirmAmount = data.getDoubleExtra("minConfirmAmount", 0);
            maxConfirmAmount = data.getDoubleExtra("maxConfirmAmount", 0);
            processStatus = data.getStringExtra("processStatus");
            loadFirst();
        }
    }

    @Override
    public void loadFirst() {
        pageNo = 1;
        getCreditorList(true);
    }

    @Override
    public void loadNext() {
        getCreditorList(false);
    }

    /**
     * 获取成员
     */
    public void getCreditorList(final boolean isFirst) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        if(processStatus == null || "".equalsIgnoreCase(processStatus))
        {
            if("1".equalsIgnoreCase(seltype))
            {
                processStatus = "5,6,7,8";
            }else {
                processStatus = "5,6,7,8";
//                processStatus = "0,1,2,3,4,5,6,7,8";
            }
        }
        Map<String, String> parms = new HashMap<>();
        parms.put("userToken", getUserToken());
        parms.put("projectId", projectId);
        parms.put("pageNo", pageNo + "");
        parms.put("pageSize", pageSize + "");
//        parms.put("committee", "true");
        if (committee != null) parms.put("committee", committee == 2 ? "true" : "false");
        if (onlineStatus != null) parms.put("onlineStatus", onlineStatus + "");
        if (kindTax != null) parms.put("kindTax", kindTax + "");
        if (kindGuarantee != null) parms.put("kindGuarantee", kindGuarantee + "");
        if (kindOther != null) parms.put("kindOther", kindOther + "");
        if (kindOrdinary != null) parms.put("kindOrdinary", kindOrdinary + "");
        if (minAmountDeclared != null && minAmountDeclared != 0f) parms.put("minAmountDeclared", minAmountDeclared + "");
        if (maxAmountDeclared != null && maxAmountDeclared != 0f) parms.put("maxAmountDeclared", maxAmountDeclared + "");
        if (minConfirmAmount != null && minConfirmAmount != 0f) parms.put("minConfirmAmount", minConfirmAmount + "");
        if (maxConfirmAmount != null && maxConfirmAmount != 0f) parms.put("maxConfirmAmount", maxConfirmAmount + "");
        if (processStatus != null) parms.put("processStatus", processStatus + "");
        if (!TextUtils.isEmpty(orderBy)) parms.put("orderBy", orderBy + "");
        if (!TextUtils.isEmpty(orderColumn)) parms.put("orderColumn", orderColumn + "");

        Network.getAPIService()
                .getCreditorListNew(parms)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            recyclerView.onFinishRequest(false, true);
                            super.onError(new Throwable(json.get("msg").getAsString()));
                            return;
                        } else {
                            recyclerView.onFinishRequest(false, true);
                            if (isFirst) {
                                userList.clear();
                            }

                            JsonObject data = json.getAsJsonObject("data");
                            JsonObject pagination = data.getAsJsonObject("pagination");
                            JsonArray array = pagination.getAsJsonArray("list");
                            List<CrediterNewUser> temp = new ArrayList<>();
                            for (int i = 0;i < array.size();i++) {
                                CrediterNewUser item = new Gson().fromJson(array.get(i), CrediterNewUser.class);
                                item.setConfirmedMoney(item.getConfirmAmount());
                                if (isAll)
                                    selectIds.add(item.getId());

                                if (selectIds.contains(item.getId())) {
                                    item.isCheck = true;
                                } else
                                    item.isCheck = false;
                                temp.add(item);
                            }


                            userList.addAll(temp);
                            int count = pagination.get("totalCount").getAsInt();
                            recyclerView.onFinishRequest(false, userList.size() < count);
                            pageNo++;

                            if(isFirst) {
                                isAll = true;
                                all_select.setText(isAll ? "取消" : "全选");
                                adapter.setAllSelect(isAll);
                                selectIds.clear();
                                if (isAll) {
                                    for (CrediterNewUser idStr : userList) {
                                        selectIds.add(idStr.getId());
                                    }
                                }
                                menu.setText("完成(" + selectIds.size() + ")");

                            }
                            adapter.notifyDataSetChanged();

                        }
                    }

                    @Override
                    public void onCompleted() {
                        recyclerView.onFinishRequest(false, true);
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        recyclerView.onFinishRequest(true, false);
                    }
                });
    }
}
